package com.itheima.leetcode;

/**
 * 有序链表去重
 *
 * @FileName E05LeetCode82
 * @Description
 * @Author Sword
 * @date 2025-03-24
 **/
public class E05LeetCode82 {

    //方法一
    public static ListNode deleteDuplicates1(ListNode p) {
        if (p == null || p.next == null) {
            return p;
        }

        if (p.val == p.next.val) {
            ListNode x = p.next.next;
            while (x != null && p.val == x.val) {
                x = x.next;
            }
            return deleteDuplicates1(x);     // 就是与p取值不同的节点
        } else {
            p.next = deleteDuplicates1(p.next);
            return p;
        }
    }

    public static ListNode deleteDuplicates2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }

        ListNode s = new ListNode(-1, head);
        ListNode p1 = s;
        ListNode p2, p3;

        while ((p2 = p1.next) != null && (p3 = p2.next) != null) {
            if (p2.val == p3.val) {
                while ((p3 = p3.next) != null && p3.val == p2.val) {

                }
                //p3 找到了不重复值
                p1.next = p3;
            } else {
                p1 = p1.next;
            }
        }
        return s.next;
    }

    public static void main(String[] args) {
        ListNode listNode = ListNode.of(1, 1, 1, 2, 3, 4, 4);
//        ListNode p = E05LeetCode82.deleteDuplicates1(listNode);
        ListNode p = E05LeetCode82.deleteDuplicates2(listNode);
        System.out.println(p);
    }
}
